package com.budwk.app.sqfwV2.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwCloudBusinessConstants;
import com.budwk.app.sqfw.dto.SqfwCompleteFlowUpdateDTO;
import com.budwk.app.sqfw.dto.SqfwServiceRecordUpdateDTO;
import com.budwk.app.sqfw.dto.TransferServiceRecordDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.tencent.TCyysb;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplateExcelCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplatePdfCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwDoc.codeGeneratorV2.excelService.CompleteFlowExcelService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.centuryCity.CenturyCitySecurityPdfService;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.vo.DocumentDownVo;
import com.budwk.app.sqfwV2.dto.vo.QueryCondititonVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.FileServiceConfigEnum;
import com.budwk.app.sqfwV2.enums.FileServiceEnum;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sqfwV2.service.childrenVisitation.ChildrenVisitationExcelService;
import com.budwk.app.sqfwV2.service.landscapePatrol.LandscapePatrolExcelService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityExcelService;
import com.budwk.app.sqfwV2.service.shawenTown.ShawenTownSafetyExcelService;
import com.budwk.app.sqfwV2.service.wasteCategoryNew.WasteCategoryNewExcelService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.DateUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.stream.Collectors;

@IocBean
@Slf4j
public class SummarySafetyCommponent {

    @Inject
    private SysUserService userService;
    @Inject
    private HuaweiOssService huaweiOssService;
    @Inject
    private PropertiesProxy propertiesProxy;
    @Inject
    private SqfwWorkorderService sqfwWorkorderService;
    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;

    public static void checkUser() {
        SysUserService sysUserService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (sysUser == null) {
            throw new AppException("用户未登陆！");
        }
        if (StringUtils.isEmpty(sysUser.getProvince())) {
            throw new AppException("用户五级信息不全，请补充！");
        }
        if (StringUtils.isEmpty(sysUser.getCity())) {
            throw new AppException("用户五级信息不全，请补充！");
        }
        if (StringUtils.isEmpty(sysUser.getDistrict())) {
            throw new AppException("用户五级信息不全，请补充！");
        }
        if (StringUtils.isEmpty(sysUser.getCounty())) {
            throw new AppException("用户五级信息不全，请补充！");
        }
        if (StringUtils.isEmpty(sysUser.getCommunity())) {
            throw new AppException("用户五级信息不全，请补充！");
        }
        if (StringUtils.isEmpty(sysUser.getUnitId())) {
            throw new AppException("用户单位信息不全，请补充！");
        }
        if (StringUtils.isEmpty(sysUser.getUnitName())) {
            throw new AppException("用户单位信息不全，请补充！");
        }
    }

    public CompleteFlowPdfParamForController buildSubmitParam(TemplateCodeUpdateDTO dto) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        // 组装参数
        CompleteFlowTemplateCodeUpdateDTO codeUpdateDTO = new CompleteFlowTemplateCodeUpdateDTO();
        codeUpdateDTO.setCompleteFlow(dto.getCompleteFlow());
        codeUpdateDTO.setFormSummary(dto.getFormSummary());
        param.setCompleteFlowDataDTO(codeUpdateDTO);
        param.setUserId(SecurityUtil.getUserId());
        return param;
    }

    public CompleteFlowCommonPdfService getCompleteFlowCommonPdfService(TemplateCodeUpdateDTO dto) {
        String type = dto.getFormSummary().getType();
        if (StringUtils.isEmpty(type)) {
            throw new AppException("请传递数据类型！");
        }
        Class<? extends CompleteFlowCommonPdfService> service = FileServiceEnum.getServiceByFillType(type);
        if (service != null) {
            return NutzIocUtils.getBean(service);
        }
        return null;
    }

    public SqfwTemplatePdfCommonService getSqfwTemplatePdfCommonService(TemplateCodeUpdateDTO dto) {
        String type = dto.getFormSummary().getType();
        if (StringUtils.isEmpty(type)) {
            throw new AppException("请传递数据类型！");
        }
        // 安全排查
        if (SupportBusinessTypeEnum.SAFETY_CHECK.getName().equals(type)) {
            if (StringUtils.isEmpty(dto.getSource())) {
                throw new AppException("数据来源source参数不能为空！");
            }
            if (CommonConstants.DAYINGROAD.equals(dto.getSource())) {
                summarySafetyCommponent.createOneTask(dto, "1", SupportBusinessTypeEnum.SAFETY_CHECK.getName());
                return NutzIocUtils.getBean(FireSafetyOnDayingRoadPdfService.class);
            }
        }
        // 安全排查整治
        if (SupportBusinessTypeEnum.SAFE_CHECK.getName().equals(type)) {
            if (StringUtils.isBlank(dto.getSource())) {
                throw new AppException("数据来源source参数不能为空！");
            }
            if (CommonConstants.SHI_JI_CHENG.equals(dto.getSource())) {
                summarySafetyCommponent.createOneTask(dto, null, SupportBusinessTypeEnum.SAFE_CHECK.getName());
                return NutzIocUtils.getBean(CenturyCitySecurityPdfService.class);
            }
        }
        return null;
    }

    public SqfwTemplateExcelCommonService getSqfwTemplateExcelCommonService1(DownExcelLedgerReqVo reqVo) {
        String fileType = reqVo.getFileType();
        if (StringUtils.isEmpty(fileType)) {
            return null;
        }
        if (SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName().equals(fileType)) {
            return NutzIocUtils.getBean(WasteCategoryNewExcelService.class);
        }
        // 如果是安全排查
        if (SupportBusinessTypeEnum.SAFETY_CHECK.getName().equals(fileType)) {
            if (StringUtils.isEmpty(reqVo.getSource())) {
                throw new AppException("数据来源source参数不能为空！");
            }
            if (CommonConstants.DAYINGROAD.equals(reqVo.getSource())) {
                return NutzIocUtils.getBean(FireSafetyOnDayingRoadExcelService.class);
            }
        }
        if (ShawenTownComponent.FILL_TYPE.equals(fileType)) {
            return NutzIocUtils.getBean(ShawenTownSafetyExcelService.class);
        }
        // 如果是社会治安
        if (SupportBusinessTypeEnum.PUBLIC_SECURITY.getName().equals(fileType)) {
            if (StringUtils.isEmpty(reqVo.getSource())) {
                throw new AppException("数据来源source参数不能为空！");
            }
            if (CommonConstants.DAYROAD_PUBLICSECURITY.equals(reqVo.getSource())) {
                return NutzIocUtils.getBean(PublicSecurityExcelService.class);
            }
        }
        if (SupportBusinessTypeEnum.CHILDREN_VISITATION.getName().equals(fileType)) { // 儿童探访记录
            return NutzIocUtils.getBean(ChildrenVisitationExcelService.class);
        }
        return null;
    }

    public List<GenerateExcelUrlVO> downExcel1(DownExcelLedgerReqVo reqVo) {
        SqfwTemplateExcelCommonService excelCommonService = getSqfwTemplateExcelCommonService1(reqVo);
        if (excelCommonService != null) {
            reqVo.setExcelCodes(List.of(reqVo.getFileCode()));
            List<ExcelCreateConfig> excelConfigList = CommonComponent.getExcelConfigList(reqVo);
            List<GenerateExcelUrlVO> generateExcelUrlVOS = excelCommonService.generateExcelForAdmin(excelConfigList, SecurityUtil.getUserId(), reqVo.getIds());
            return generateExcelUrlVOS;
        }
        return Lists.newArrayList();
    }

    public List<GenerateExcelUrlVO> downExcel2(DownExcelLedgerReqVo reqVo) {
        CompleteFlowExcelService excelCommonService = getSqfwTemplateExcelCommonService2(reqVo);
        if (excelCommonService != null) {
            // 组装数据
            CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
            paramForController.setFormSummaryIdList(reqVo.getIds());
            List<ExcelCreateConfig> excelCreateConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(reqVo.getFileCode());
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            // 下载数据
            List<ResultOfExcelGenerator> excelGenerators = excelCommonService.createExcelForAdmin(paramForController);

            List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
            if (CollectionUtil.isEmpty(excelGenerators)) {
                return Lists.newArrayList();
            }
            // 组装数据返回
            for (ResultOfExcelGenerator excelGenerator : excelGenerators) {
                GenerateExcelUrlVO excelUrlVO = new GenerateExcelUrlVO();
                excelUrlVO.setExcelUrl(excelGenerator.getExcelUrl())
                        .setUrl(excelGenerator.getExcelUrl())
                        .setFileIdentity(excelGenerator.getFileIdentity())
                        .setNotCreateMark(excelGenerator.getNotCreateMark());
                generateExcelUrlVOS.add(excelUrlVO);
            }
            return generateExcelUrlVOS;
        }
        return Lists.newArrayList();
    }

    public CompleteFlowExcelService getSqfwTemplateExcelCommonService2(DownExcelLedgerReqVo reqVo) {
        String fileType = reqVo.getFileType();
        if (StringUtils.isEmpty(fileType)) {
            return null;
        }
        if (SupportBusinessTypeEnum.FOREST_AND_RIVER_FLOOD_DISASTER.getName().equals(fileType)) {
            return NutzIocUtils.getBean(LandscapePatrolExcelService.class);
        }
        return null;
    }

    public Result<?> listByConditionKey(String fillType, String address, String placeName) {
        if (SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName().equals(fillType)) {
            // 垃圾分类
            List<Sqfw_formSummary_new> list = WasteCategoryComponent.listByConditionKey(address, fillType);
            return Result.data(list);
        }
        if (SupportBusinessTypeEnum.FOREST_AND_RIVER_FLOOD_DISASTER.getName().equals(fillType)) {
            List<Sqfw_formSummary_new> list = WasteCategoryComponent.listByConditionKey(address, fillType);
            return Result.data(list);
        }
        return Result.success();
    }

    public List<DownFileTypesResVo> generateFile(List<Sqfw_formSummary_new> formSummarys, SummaryQueryReqVo reqVo) {
        if (SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName().equals(reqVo.getFillType())) { // 垃圾分类
            return WasteCategoryComponent.generateFile(formSummarys);
        }
        List<DownFileTypesResVo> resVos = SummarySafetyCommponent.generateFileList(formSummarys, reqVo.getFillType());
        if (CollectionUtil.isNotEmpty(resVos)) {
            return resVos;
        }
        if (SupportBusinessTypeEnum.FOREST_AND_RIVER_FLOOD_DISASTER.getName().equals(reqVo.getFillType())) { // 林河汛灾防治
            return LandscapePatrolComponent.generateFile(formSummarys);
        }
        // 安全排查
        if (SupportBusinessTypeEnum.SAFETY_CHECK.getName().equals(reqVo.getFillType())) {
            if (CommonConstants.DAYINGROAD.equals(reqVo.getSource())) {
                return DayingRoadPdfComponent.generateFiles(formSummarys);
            }
        }
        // 社会治安
        if (SupportBusinessTypeEnum.PUBLIC_SECURITY.getName().equals(reqVo.getFillType())) {
            return PublicSecurityComponent.generateFiles(reqVo, formSummarys);
        }
        return Lists.newArrayList();
    }

    public DownFileTypesResVo generateDetailFile(List<Sqfw_formSummary_new> formSummarys, SummaryQueryReqVo reqVo) {
        if (SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName().equals(reqVo.getFillType())) { // 垃圾分类
            return WasteCategoryComponent.generateDetailFile(formSummarys, reqVo);
        }
        DownFileTypesResVo resVo = SummarySafetyCommponent.generateDetailFileList(formSummarys, reqVo);
        if (resVo != null) {
            return resVo;
        }
        if (SupportBusinessTypeEnum.FOREST_AND_RIVER_FLOOD_DISASTER.getName().equals(reqVo.getFillType())) { // 林河汛灾防治
            return LandscapePatrolComponent.generateDetailFile(formSummarys, reqVo);
        }
        // 安全排查
        if (SupportBusinessTypeEnum.SAFETY_CHECK.getName().equals(reqVo.getFillType())) {
            if (CommonConstants.DAYINGROAD.equals(reqVo.getSource())) {
                return DayingRoadPdfComponent.generateDetailFile(formSummarys, reqVo);
            }
        }
        return null;
    }

    public DownFileTypesResVo downTemplate(DownExcelLedgerReqVo reqVo) {
        String fileType = reqVo.getFileType();
        if (StringUtils.isEmpty(fileType)) {
            throw new AppException("文件类型不能为空！");
        }
        if (StringUtils.isEmpty(reqVo.getFileCode())) {
            throw new AppException("文件code不能为空！");
        }
        if (SupportBusinessTypeEnum.REFUSE_CLASSIFY.getName().equals(reqVo.getFileType())) { // 垃圾分类
            return WasteCategoryComponent.downTemplate(reqVo);
        }
        List<FileServiceConfigEnum> list = FileServiceConfigEnum.findByFillType(reqVo.getFileType(), null);
        if (CollectionUtil.isNotEmpty(list)) {
            return downTemplateFile(reqVo);
        }
        if (SupportBusinessTypeEnum.FOREST_AND_RIVER_FLOOD_DISASTER.getName().equals(reqVo.getFileType())) { // 林河汛灾防治
            return LandscapePatrolComponent.downTemplate(reqVo);
        }
        // 安全排查
        if (SupportBusinessTypeEnum.SAFETY_CHECK.getName().equals(reqVo.getFileType())) {
            if (CommonConstants.DAYINGROAD.equals(reqVo.getSource())) {
                return DayingRoadPdfComponent.downTemplate(reqVo);
            }
        }
        return new DownFileTypesResVo();
    }

    /**
     * 下载word模板代码
     *
     * @param reqVo
     * @param generator
     * @param filePath
     * @param pdfCreateCommonBO
     * @param fileName
     * @return
     */
    public static Sqfw_form_summary_pdf downWordTemplate(DownExcelLedgerReqVo reqVo, BaseTemplatePdfGenerator generator, String filePath, SqfwPdfCreateCommonBO pdfCreateCommonBO, String fileName) {
        String downFileName = String.format("%s%s", fileName, "模板");
        pdfCreateCommonBO.setDownTemplate(true);
        boolean againGenerate = reqVo.isAgainGenerate();
        if (againGenerate) {
            return downTemplate(reqVo, generator, filePath, pdfCreateCommonBO, downFileName);
        }
        // 从历史任务中获取
        String title = String.format("%s%s", downFileName, SecurityUtil.getUserId());
        SqfwDownRecordlogService sqfwDownRecordlogService = NutzIocUtils.getBean(SqfwDownRecordlogService.class);
        Optional<String> optional = sqfwDownRecordlogService.getUrlByEntityIdAndTitle(reqVo.getIds().get(0), title);
        if (optional.isPresent()) {
            log.info("downDocTemplate filename: {}, url: {}", downFileName, optional.get());
            Sqfw_form_summary_pdf summaryNew = new Sqfw_form_summary_pdf();
            summaryNew.setUrl(optional.get());
            return summaryNew;
        }
        return downTemplate(reqVo, generator, filePath, pdfCreateCommonBO, downFileName);
    }

    private static Sqfw_form_summary_pdf downTemplate(DownExcelLedgerReqVo reqVo, BaseTemplatePdfGenerator generator, String filePath, SqfwPdfCreateCommonBO pdfCreateCommonBO, String downFileName) {
        // 2 初始化参数
        Map<String, Object> map = new HashMap<>();
        generator.customerPopularPdfParam(map, pdfCreateCommonBO);
        // 3 下载文件
        ByteArrayOutputStream pdfOS = CommonFormOfficeUtils.generateWordDocument(map, filePath, null, System.currentTimeMillis());
        GenerateWordAndPdfUrlVO wordPdfResult = CommonFormOfficeUtils.wordUpload(pdfOS, downFileName, "");
        // 3 记录下载日志
        String title = String.format("%s%s", downFileName, SecurityUtil.getUserId());
        CommonComponent.insertDownRecordLog(null, JSONObject.toJSONString(Result.data(wordPdfResult)),
                title, wordPdfResult != null ? wordPdfResult.getWordUrl() : null, reqVo.getIds().get(0));
        // 5 组装数据返回
        Sqfw_form_summary_pdf summaryNew = new Sqfw_form_summary_pdf();
        if (wordPdfResult != null) {
            summaryNew.setUrl(wordPdfResult.getWordUrl());
        }
        return summaryNew;
    }

    public static String getCustomerNeed(String dataSource, String type) {
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user user = userService.fetch(SecurityUtil.getUserId());
        if (StringUtils.isEmpty(dataSource)) {
            return String.format("%s%s%s%s", user.getCounty(), user.getCommunity(), type, "任务【2024】");
        }
        // 大营路比较特殊
        if ("1".equals(dataSource)) {
            return "大营路安全排查整治任务【2024】";
        }
        return String.format("%s%s%s%s", user.getCounty(), user.getCommunity(), type, "任务【2024】");
    }

    public void createOneTask(TemplateCodeUpdateDTO dto, String dataSource, String type) {
        String userId = SecurityUtil.getUserId();
        log.info("---------createOneTask----createOneTask-----------: userId : {}", userId);
        SqfwCompleteFlowUpdateDTO completeFlow = dto.getCompleteFlow();
        // 走原有逻辑
        if (completeFlow != null) {
            return;
        }
        Sys_user user = userService.fetch(SecurityUtil.getUserId());
        SummarySafetyService summarySafetyService = NutzIocUtils.getBean(SummarySafetyService.class);
        Sqfw_formSummary_new formSummary = dto.getFormSummary();
        if (StringUtils.isEmpty(formSummary.getType())) {
            formSummary.setType(type);
        }
        // 查询是否已创建任务
        Sqfw_servicerecord servicerecord = summarySafetyService.queryCurrentTask(dataSource, formSummary.getType());
        if (servicerecord != null) {
            Sqfw_workorder worker = sqfwWorkorderService.fetch(Cnd.where(Sqfw_workorder::getSqfw_id, "=", servicerecord.getId()));
            if (worker != null) {
                formSummary.setWorkOrderId(worker.getId()).setSqfwId(servicerecord.getId());
                dto.setFormSummary(formSummary);
            }
            return;
        }
        // 2 创建任务
        SqfwServiceRecordUpdateDTO sqfwServicerecord = new SqfwServiceRecordUpdateDTO();
        // 避免id存在 需要检查id是否可用
        if (StringUtils.isNotEmpty(dataSource) && "1".equals(dataSource)) {
            sqfwServicerecord.setType("安全排查整治");
            sqfwServicerecord.setRecording_text("消防安全定期排查任务，请大家尽快完成");
            sqfwServicerecord.setLocalAudioTransText("消防安全定期排查任务，请大家尽快完成");
        } else {
            sqfwServicerecord.setType(formSummary.getType());
            sqfwServicerecord.setRecording_text("定期排查任务，请大家尽快完成");
            sqfwServicerecord.setLocalAudioTransText("定期排查任务，请大家尽快完成");
        }
        sqfwServicerecord.setRecording_text("定期排查消防任务，请大家尽快完成");
        sqfwServicerecord.setLocalAudioTransText("定期排查消防任务，请大家尽快完成");
        sqfwServicerecord.setCustomer_need(getCustomerNeed(dataSource, formSummary.getType()));
        sqfwServicerecord.setConnect_time(new Date());
        sqfwServicerecord.setCustomer_name(SecurityUtil.getUserUsername());
        sqfwServicerecord.setService_name(SecurityUtil.getUserUsername());
        sqfwServicerecord.setCustomer_phone(user.getMobile());
        sqfwServicerecord.setService_phone(user.getMobile());
        sqfwServicerecord.setUser_id(user.getId());
        sqfwServicerecord.setApp_type("7");
        sqfwServicerecord.setCompanyName(user.getUnitName());
        sqfwServicerecord.setCloudTransFlag(false);
        Sqfw_workorder worker = createTask(sqfwServicerecord);
        formSummary.setWorkOrderId(worker.getId()).setSqfwId(worker.getSqfw_id());
        dto.setFormSummary(formSummary);
    }

    private Sqfw_workorder createTask(SqfwServiceRecordUpdateDTO sqfwServicerecord) {
        Sys_user sysUser = userService.fetch(SecurityUtil.getUserId());

        // wzy 2023-11-22 从后端查出用户数据进行赋值地级市5级数据
        sqfwServicerecord.setProvince(sysUser.getProvince());
        sqfwServicerecord.setCity(sysUser.getCity());
        sqfwServicerecord.setDistrict(sysUser.getDistrict());
        sqfwServicerecord.setCounty(sysUser.getCounty());
        sqfwServicerecord.setCommunity(sysUser.getCommunity());
        sqfwServicerecord.setCreatedBy(SecurityUtil.getUserId());
        String getPhone = sqfwServicerecord.getService_phone();
        sqfwServicerecord.setDelFlag(false);

        // 赋值关于语音时常相关属性
        if (!StringUtils.isNotBlank(sqfwServicerecord.getService_phone()) && sqfwServicerecord.getDuration() != null) {
            long audioDuration = sqfwServicerecord.getDuration() / 1000;
            sqfwServicerecord.setDuration(audioDuration);
            Date endTime = new Date(sqfwServicerecord.getConnect_time().getTime() + audioDuration);
            sqfwServicerecord.setEnd_time(endTime);
        }
        sqfwServicerecord.setRecording_text(sqfwServicerecord.getRecording_text());
        sqfwServicerecord.setService_phone(null);
        sqfwServicerecord.setService_name(null);
        sqfwServicerecord.setFinishStatus("new");

        // 处理语音转文字相关事情
        Sqfw_cloudcallback cloudCallBack = handleVideoTransTextAtServiceRecordCreate(sqfwServicerecord);

        SqfwServicerecordService sqfwServicerecordService = NutzIocUtils.getBean(SqfwServicerecordService.class);
        SqfwCloudcallbackService sqfwCloudcallbackService = NutzIocUtils.getBean(SqfwCloudcallbackService.class);
        Sqfw_servicerecord newServiceOrder = sqfwServicerecordService.insert(sqfwServicerecord);

        if (cloudCallBack != null) {
            cloudCallBack.setBusinessId(newServiceOrder.getId());
            sqfwCloudcallbackService.insert(cloudCallBack);
        }

        // 新增语音通话需要生成一个工单
        Sqfw_workorder workOrder = new Sqfw_workorder();
        workOrder.setSqfw_id(newServiceOrder.getId());
        workOrder.setUser_name(sysUser.getUsername());
        workOrder.setWk_grade("0");
        workOrder.setWk_priority("take_time_complete");
        workOrder.setUser_id(newServiceOrder.getCreatedBy());
        workOrder.setCreateDate(new Date());
        workOrder.setUpdatedAt(new Date());
        workOrder.setCreatedBy(newServiceOrder.getCreatedBy());
        // wzy 2023-5-25 服务记录生成工单的时候不主动完成对应工单
        workOrder.setWk_status("new");
        // workOrder.setComplete_time(new Date());
        workOrder.setDelflag(false);
        workOrder.setServiceType(sqfwServicerecord.getType());

        SqfwWorkorderService sqfwWorkorderService = NutzIocUtils.getBean(SqfwWorkorderService.class);
        sqfwWorkorderService.insert(workOrder);

        if (StringUtils.isNotBlank(getPhone)) {
            List<String> strings = new ArrayList<>();
            TransferServiceRecordDTO dto = new TransferServiceRecordDTO();
            dto.setServiceRecordId(newServiceOrder.getId());
            List<String> list = Lists.newArrayList(getPhone.split(","));
            for (String str : list) {
                Sys_user querySysUser = userService.getUserByLoginname(str);
                strings.add(querySysUser.getId());
            }
            dto.setToSysUserIdList(strings);
            sqfwWorkorderService.transferServiceRecordNew(dto);
        }
        return workOrder;
    }

    private Sqfw_cloudcallback handleVideoTransTextAtServiceRecordCreate(SqfwServiceRecordUpdateDTO serviceRecord) {
        if (StringUtils.isNotBlank(serviceRecord.getRecording_file())
                && !serviceRecord.getApp_type().equals("7")
                && !serviceRecord.getApp_type().equals("8")) {

            Boolean cloudTransFlag = serviceRecord.getCloudTransFlag();
            cloudTransFlag = cloudTransFlag == null;
            if (cloudTransFlag) {
                // 这里会进行语音识别 分为两个分支一个是调用腾讯的语音识别，另外一个是手机本地已经识别完成，然后直接使用
                String url = huaweiOssService.getPwdPath(serviceRecord.getRecording_file());

                String serviceIp = propertiesProxy.get("jarService.ip");
                String port = propertiesProxy.get("server.port");
                String callback = StrFormatter.format("http://{}:{}/platform/sqfw/cloudcallback/callback", serviceIp, port);
                Long taskId = TCyysb.Send(url, callback);

                if (taskId != null && taskId > 0L) {
                    serviceRecord.setTaskId(taskId.toString());
                }

                return null;
            } else {
                String localAudioTransText = serviceRecord.getLocalAudioTransText();
                String localAudioTransOriText = serviceRecord.getLocalAudioTransOriText();
                serviceRecord.setRecording_text(serviceRecord.getLocalAudioTransText());

                Sqfw_cloudcallback cloudCallBack = new Sqfw_cloudcallback();
                cloudCallBack.setAudioUrl(serviceRecord.getRecording_file());
                cloudCallBack.setText(localAudioTransText);  // 这个字段存已经通过系统替换过的文本
                cloudCallBack.setResultDetail(localAudioTransOriText);
                cloudCallBack.setBusinessId(serviceRecord.getId());
                cloudCallBack.setBusinessType(SqfwCloudBusinessConstants.SERVICE_RECORD);
                cloudCallBack.setCreatedAt(new Date().getTime());
                cloudCallBack.setUpdatedAt(new Date().getTime());
                cloudCallBack.setDelFlag(false);
                cloudCallBack.setTransChannel(SqfwCloudBusinessConstants.TRANS_CHANNEL_DFSJ);
                return cloudCallBack;
            }
        }

        return null;
    }

    /**
     * 2.0公共查询组件参数
     */
    public static SqlExpressionGroup buildQueryExpression(Cnd cri, SummaryQueryReqVo reqVo) {
        SqlExpressionGroup expressionGroup = cri.where();
        if (StringUtils.isNotEmpty(reqVo.getFillType())) {
            expressionGroup.andEquals(Sqfw_formSummary_new::getType, reqVo.getFillType());
        }
        if (StringUtils.isNotEmpty(reqVo.getShopsBaseInfoId())) {
            expressionGroup.andEquals(Sqfw_formSummary_new::getShopsBaseInfoId, reqVo.getShopsBaseInfoId());
        }
        if (StringUtils.isNotEmpty(reqVo.getCreateId())) {
            expressionGroup.andEquals(Sqfw_formSummary_new::getCreateBy, reqVo.getCreateId());
        }
        if (StringUtils.isNotEmpty(reqVo.getUnitId())) {
            expressionGroup.andEquals(Sqfw_formSummary_new::getUnitId, reqVo.getUnitId());
        }
        // 用户查询权限
        List<QueryCondititonVo> queryCondititons = reqVo.getQueryCondititons();
        if (CollectionUtil.isNotEmpty(queryCondititons)) {
            List<SqlExpressionGroup> sqlExpressionGroups = new ArrayList<>();
            for (QueryCondititonVo condititonVo : queryCondititons) {
                if (StringUtils.isNotEmpty(condititonVo.getKey()) && StringUtils.isNotEmpty(condititonVo.getValue())) {
                    // 如果为空 默认按照=号查询
                    if (StringUtils.isEmpty(condititonVo.getFlag())) {
                        SqlExpressionGroup conGroup = Cnd.exps(new Static("param_data->>'" + condititonVo.getKey() + "' = '" + condititonVo.getValue() + "'"));
                        sqlExpressionGroups.add(conGroup);
                        continue;
                    }
                    if (condititonVo.getFlag().equals("like")) {
                        SqlExpressionGroup conGroup = Cnd.exps(new Static("param_data->>'" + condititonVo.getKey() + "' " + condititonVo.getFlag() + " '%" + condititonVo.getValue() + "%'"));
                        sqlExpressionGroups.add(conGroup);
                        continue;
                    }
                    SqlExpressionGroup conGroup = Cnd.exps(new Static("param_data->>'" + condititonVo.getKey() + "' " + condititonVo.getFlag() + " '" + condititonVo.getValue() + "'"));
                    sqlExpressionGroups.add(conGroup);
                }
            }
            if (sqlExpressionGroups.size() > 0) {
                SqlExpressionGroup sg = sqlExpressionGroups.get(0);
                ;
                for (int i = 1; i < sqlExpressionGroups.size(); i++) {
                    sg = sg.or(sqlExpressionGroups.get(i));
                }
                expressionGroup.and(sg);
            }
        }
        if (StringUtils.isNotEmpty(reqVo.getByMainBussiness())) {
            SqlExpressionGroup sg = Cnd.exps(new Static("param_data->'smallBusinessEstablishment'->>'mainBusinessScope' like '%" + reqVo.getByMainBussiness() + "%'"));
            expressionGroup.and(sg);
        }
        //自定义sql(内部调用)
        if (ObjectUtils.isNotEmpty(reqVo.getSqlExpressionGroup())) {
            expressionGroup.and(reqVo.getSqlExpressionGroup());
        }
        // 人员类型
        if (StringUtils.isNotEmpty(reqVo.getSpecialMarkStr())) {
            expressionGroup.and("(special_mark::text)", "like", "%\"key\": "+ reqVo.getSpecialMarkStr() + "%");
        }
        if (StringUtils.isNotEmpty(reqVo.getSort())) {
            cri.orderBy(Sqfw_formSummary_new::getFillDate, reqVo.getSort());
        } else {
            // 默认按照降序
            cri.orderBy(Sqfw_formSummary_new::getFillDate, "desc");
        }
        return expressionGroup;
    }

    /**
     * 查询当月数据的条数
     *
     * @param list
     * @param dto
     * @return
     */
    public int queryCurrentTotal(List<Sqfw_formSummary_new> list, SummaryQueryReqVo dto) {
        Sqfw_formSummary_new summaryNew = list.get(list.size() - 1);
        // 查询当前月份的所有数据
        Date queryFillDate = summaryNew.getFillDate();
        queryFillDate = queryFillDate == null ? new Date() : queryFillDate;
        // 获取当前时间节点的最后一天
        String lastMonthDay = DateUtils.getCurrentDataLastDay(queryFillDate);
        Cnd cri1 = Cnd.NEW();
        dto.setCreateId(SecurityUtil.getUserId());
        SqlExpressionGroup expressionGroup1 = SummarySafetyCommponent.buildQueryExpression(cri1, dto);
        String fillDate = DateUtil.format(queryFillDate, DatePattern.NORM_MONTH_PATTERN);
        expressionGroup1.andBetween(Sqfw_formSummary_new::getFillDate, fillDate + "-01 00:00:00", lastMonthDay);
        SummarySafetyService safetyService = NutzIocUtils.getBean(SummarySafetyService.class);
        return safetyService.count(cri1);
    }


    public static List<DownFileTypesResVo> generateFileList(List<Sqfw_formSummary_new> formSummarys, String fillType) {
        List<DownFileTypesResVo> list = new ArrayList<>();
        // 获取所有的下载文件
        List<FileServiceConfigEnum> configEnums = FileServiceConfigEnum.findByFillType(fillType, null);
        for (FileServiceConfigEnum configEnum : configEnums) {
            SummaryQueryReqVo queryReqVo = new SummaryQueryReqVo();
            queryReqVo.setFillType(fillType).setFileCode(configEnum.getCode());
            DownFileTypesResVo resVo = generateDetailFileList(formSummarys, queryReqVo);
            if (resVo != null) {
                list.add(resVo);
            }
        }
        return list;
    }

    public static DownFileTypesResVo generateDetailFileList(List<Sqfw_formSummary_new> formSummarys, SummaryQueryReqVo queryReqVo) {
        List<FileServiceConfigEnum> list = FileServiceConfigEnum.findByFillType(queryReqVo.getFillType(), null);
        Optional<FileServiceConfigEnum> pdfs = list.stream().filter(e -> e.getCode().equals(queryReqVo.getFileCode())).findFirst();
        if (pdfs.isEmpty()) {
            return null;
        }
        FileServiceConfigEnum serviceConfig = pdfs.get();
        DownExcelLedgerReqVo reqVo = new DownExcelLedgerReqVo();
        reqVo.setDownTemplate(true)
                .setAgainGenerate(queryReqVo.isAgainGenerate())
                .setFileType(queryReqVo.getFillType())
                .setFileCode(serviceConfig.getCode())
                .setDownFileType(serviceConfig.getFileType());
        // 组装数据返回
        DownFileTypesResVo resVo = new DownFileTypesResVo();
        resVo.setLocation(serviceConfig.getLocation())
                .setFileType(serviceConfig.getFileType())
                .setPreviewImage(List.of(serviceConfig.getPreviewImage().split(",")))
                .setFileName(serviceConfig.getFileName()+".pdf")
                .setFileCode(serviceConfig.getCode())
                .setHiveData(formSummarys.size() > 0)
                .setLabel(serviceConfig.getLabel())
                .setCreatedAt(System.currentTimeMillis());

        if (CommonConstants.PDF.equals(serviceConfig.getFileType())) {
            DownFileTypesResVo downTemplate = downTemplateFile(reqVo);
            resVo.setFileName(serviceConfig.getFileName()+".pdf").setFileTemplatePath(downTemplate.getFilePath())
                    .setIds(formSummarys.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList()));
            return resVo;
        }
        if (CommonConstants.EXCEL.equals(serviceConfig.getFileType())) {
            resVo.setFileName(serviceConfig.getFileName()+".xlsx").setIds(formSummarys.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            DownFileTypesResVo resVo1 = downTemplateFile(reqVo);
            resVo.setFileTemplatePath(resVo1.getFilePath());
            if (serviceConfig.getFillType().equals(SupportBusinessTypeEnum.BATYUN_SAFE.getName())) {
                ShawenTownComponent.checkFormSummarysData(serviceConfig, resVo, formSummarys);
            }
        }
        return resVo;
    }

    public static DownFileTypesResVo downTemplateFile(DownExcelLedgerReqVo reqVo) {
        FileServiceConfigEnum serviceConfig = FileServiceConfigEnum.findByCode(reqVo.getFileType(), reqVo.getFileCode());
        reqVo.setIds(List.of(serviceConfig.getTemplateId()));
        if (CommonConstants.EXCEL.equals(serviceConfig.getFileType())) {
            return DocumentDownComponent.downExcelTemplateFile(reqVo);
        }
        if (CommonConstants.PDF.equals(serviceConfig.getFileType())) {
            // 1 如果模板路劲存在 按照此方式下载
            DownFileTypesResVo resVo = DocumentDownComponent.templatePathExistDownMethod(reqVo, serviceConfig);
            if (resVo != null) {
                return resVo;
            }
            // 2 模板路径为空
            DocumentDownVo documentDownVo = DocumentDownComponent.buildWordTemplateParam(reqVo, serviceConfig); // 构造参数
            // 下载
            return DocumentDownComponent.downWordDocTemplate(documentDownVo);
        }
        return null;
    }
}
